package com.weilive.core.protocol;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import com.weilive.core.utils.GZipUtils;

public class PacketCodec {

	public static final int FLAG_NONE = 0;// 都不压缩
	public static final int FLAG_GZIP_CLIENT = 1;// 客户端压缩,服务器不压缩
	public static final int FLAG_GZIP_SERVER = 2;// 客户端不压缩,服务器压缩
	public static final int FLAG_GZIP_ALL = 3;// 都压缩

	/**
	 * 客户端请求是否压缩
	 * 
	 * @param codec
	 * @return
	 */
	public static boolean clientIsGZIP(int codec) {
		return codec == FLAG_GZIP_CLIENT || codec == FLAG_GZIP_ALL;
	}

	/**
	 * 服务器应答是否压缩
	 * 
	 * @param codec
	 * @return
	 */
	public static boolean serverIsGZIP(int codec) {
		return codec == FLAG_GZIP_SERVER || codec == FLAG_GZIP_ALL;
	}

	public static String encode(int codec, String data) throws Exception {
		String ret = data;
		if (serverIsGZIP(codec)) {
			ret = GZipUtils.compress(data);
		}
		return ret;
	}

	public static String decode(int codec, String data) throws Exception {
		String ret = data;
		if (clientIsGZIP(codec)) {
			ret = GZipUtils.uncompress(data);
		}
		return ret;
	}

	public static byte[] encode(int codec, byte[] data) throws Exception {
		byte[] ret = data;
		if (serverIsGZIP(codec)) {
			ret = GZipUtils.compress(ret);
		}
		return ret;
	}

	public static byte[] decode(int codec, byte[] data) throws Exception {
		byte[] ret = data;
		if (clientIsGZIP(codec)) {
			ret = GZipUtils.uncompress(ret);
		}
		return ret;
	}

	public static InputStream decode(int codec, InputStream data) throws Exception {
		InputStream ret = data;
		if (clientIsGZIP(codec)) {
			byte[] bs = GZipUtils.uncompress(data);
			return new ByteArrayInputStream(bs);
		}
		return ret;
	}
}
